package com.acme.bankapp.service.bank;

import java.awt.Window.Type;
import java.util.PriorityQueue;
import java.util.Queue;

import com.acme.bankapp.exceptions.ClosedQueueException;

public class BlockingQueue<Type> {
	private Queue<Type> queue = new PriorityQueue<Type>();
	private int maxQueueSize;
	private int numElementsInQueue=0;
	private boolean isQueueIsOpen=true;
	
	public BlockingQueue(int maxSize) {
		maxQueueSize = maxSize;
	} 
	
	public Type getItemAndRemove() throws InterruptedException, ClosedQueueException {
		synchronized (queue) {
			while (queue.isEmpty() ){
				exitIfsQueueIsClosed();
				queue.wait();
			}
			
			exitIfsQueueIsClosed();
			
			numElementsInQueue--;
			return queue.remove();
		}
	}
	
	public void addItem(Type item) throws InterruptedException, ClosedQueueException {
		synchronized (queue) {
			if(numElementsInQueue >= maxQueueSize){
				queue.wait();
				exitIfsQueueIsClosed();
			}
			exitIfsQueueIsClosed();
			numElementsInQueue++;
			queue.add(item);
		}
	}
	
	public void exitIfsQueueIsClosed() throws ClosedQueueException{
		if (!isQueueIsOpen){
			throw new ClosedQueueException("Queue is closed. Come back tommorow");
		}
	}
}
